﻿using System;
using System.Collections.Generic;
using System.Text;

namespace ChronoNES
{
    class Mapper
    {
        public byte[] pROM;
        public byte[] cROM;

        public byte pROMPages;
        public byte cROMPages;

        public void Init(byte _pROMPages, byte _cROMPages)
        {
            pROMPages = _pROMPages;
            cROMPages = _cROMPages;

            pROM = new byte[pROMPages * 16 * 1024];
            cROM = new byte[cROMPages * 8 * 1024];  
        }

        public byte Read(ushort _address)
        {
            if (pROMPages == 1 && _address >= 0x4000)
                _address -= 0x4000;

            return pROM[_address];
        }

        public ushort Read16(ushort _address)
        {
            if (pROMPages == 1 && _address >= 0x4000)
                _address -= 0x4000;

            return (ushort)((ushort)((ushort)pROM[_address + 1] << 8) + (ushort)pROM[_address]);
        }

        public void Write(ushort _address, byte _value)
        {
            if (pROMPages == 1 && _address >= 0x4000)
                _address -= 0x4000;

            pROM[_address] = _value;
        }

        public void Write16(ushort _address, ushort _value)
        {
            if (pROMPages == 1 && _address >= 0x4000)
                _address -= 0x4000;

            pROM[_address + 1] = (byte)(_value >> 8);
            pROM[_address] = (byte)(_value & 0xFF);
        }

        public static Mapper Create(byte _mapperID)
        {
            switch (_mapperID)
            {
                case 0x00: return new Mapper();
            }
        
            throw new Exception(String.Format("Unsupported mapper {0}", _mapperID));
        }
    }
}
